<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\models\Area;
use app\models\User;
use app\models\Identity;
use app\models\FeedBack;
use app\models\UserAuthRecord;
use app\models\CompanyInfo;
use app\models\OrderInfo;
use app\models\OrderInfoGood;
use app\models\Good;
use app\models\PhoneCode;
use app\models\Setting;
use app\models\UserLogin;
use app\models\Question;
use app\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;

class UserController extends BaseController
{
  public function behaviors() {
      $optional =  [
          'register',
          'login-by-username',
          'login-by-phone-code',
          'login-by-third-code',
          'bind-phone',
          'send-code',
          'reset-password',
      ];
      return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
          'class' => HttpBearerAuth::class,
          'optional' =>$optional
        ]
      ]);
  }

  public $state_arr = ['待付款', '待发货', '待收货', '已完成', '退款中', '退款成功', '退款失败', '已取消'];

  //账户注册
  public function actionRegister(){
    $phone = Yii::$app->request->post('phone', '');
    $code = Yii::$app->request->post('code', '');
    $password = Yii::$app->request->post('password', '');
    $con_password = Yii::$app->request->post('con_password', '');
    //$reg_id = Yii::$app->request->post('reg_id', '');
    if (empty($phone) || empty($code) || empty($password) || empty($con_password)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    if (!PhoneCode::check($phone, $code)) {
      return Re::data(null, '验证码错误', Re::ERROR);
    }
    $user_old = Identity::findOne(['phone' => $phone, 'status' => [0,1]]);
    if ($user_old) {
      return Re::data(null, '手机号已被占用', Re::ERROR);
    }
    if ($password != $con_password) {
      return Re::data(null, '两次输入的密码不一致', Re::ERROR);
    }
    $user = new Identity();
    $user->username = $phone;
    $user->password = Yii::$app->security->generatePasswordHash($password);
    $user->phone = $phone;
    //$user->reg_id = $reg_id;
    $user->status = 1;
    $user->created_at = time();
    if (!$user->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    return Re::data();
  }

  //账号登录
  public function actionLoginByUsername(){
    $phone = Yii::$app->request->post('phone', '');
    $password = Yii::$app->request->post('password', '');
    $user = Identity::findOne(['username' => $phone, 'status' => 1]);
    if($user && Yii::$app->security->validatePassword($password, $user->password)){
      $data = $this->returnUserInfo($user, 1);
      return Re::data(['data' => $data]);
    } else {
      return Re::data(null, '用户名或密码错误', Re::ERROR);
    }
  }

  //手机验证码登录
  public function actionLoginByPhoneCode(){
    $phone = Yii::$app->request->post('phone', '');
    $code = Yii::$app->request->post('code', '');
    if (empty($phone) || empty($code)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    if (!PhoneCode::check($phone, $code)) {
      return Re::data(null, '验证码错误', Re::ERROR);
    }
    $user = Identity::findOne(['phone' => $phone, 'status' => 1]);
    if($user){
      $data = $this->returnUserInfo($user, 2);
      return Re::data(['data' => $data]);
    } else {
      return Re::data(null, '用户信息读取失败', Re::ERROR);
    }
  }

  //第三方账户登录
  public function actionLoginByThirdCode(){
    $login_type = Yii::$app->request->post('login_type', 3);
    $login_code = Yii::$app->request->post('login_code', '');
    if (empty($login_code)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    if ($login_type == 3) {
      $user = Identity::findOne(['openid_qq' => $login_code, 'status' => [0,1]]);
    } else if ($login_type == 4) {
      $user = Identity::findOne(['openid_wx' => $login_code, 'status' => [0,1]]);
    } else if ($login_type == 5) {
      $user = Identity::findOne(['openid_wb' => $login_code, 'status' => [0,1]]);
    }
    $data = $this->returnUserInfo($user, $login_type);
    return Re::data(['data' => $data]);
  }

  //第三方账户绑定手机号
  public function actionBindPhone(){
    $phone = Yii::$app->request->post('phone', '');
    $code = Yii::$app->request->post('code', '');
    $login_type = Yii::$app->request->post('login_type', 3);
    $login_code = Yii::$app->request->post('login_code', '');
    if (empty($phone) || empty($code) || empty($login_type) || empty($login_code)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    if (!PhoneCode::check($phone, $code)) {
      return Re::data(null, '验证码错误', Re::ERROR);
    }
    $user = Identity::findOne(['phone' => $phone, 'status' => [0,1]]);
    if (!$user) {
      $user = new Identity();
    }
    $user->username = $phone;
    $user->phone = $phone;
    $user->status = 1;
    $user->created_at = time();
    if ($login_type == 3) {
      $user->openid_qq = $login_code;
    } else if ($login_type == 4) {
      $user->openid_wx = $login_code;
    } else if ($login_type == 5) {
      $user->openid_wb = $login_code;
    }
    if (!$user->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    $user->save();
    $data = $this->returnUserInfo($user, $login_type);
    return Re::data(['data' => $data]);
  }

  //登录状态下绑定第三方账户
  public function actionBindThirdCode(){
    $login_type = Yii::$app->request->post('login_type', 3);
    $login_code = Yii::$app->request->post('login_code', '');
    if (empty($login_type) || empty($login_code)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    $user = Yii::$app->user->identity;
    if ($login_type == 3) {
      $user->openid_qq = $login_code;
    } else if ($login_type == 4) {
      $user->openid_wx = $login_code;
    } else if ($login_type == 5) {
      $user->openid_wb = $login_code;
    }
    $user->save();
    return Re::data();
  }

  //第三方账户解绑
  public function actionThirdReset(){
    $login_type = Yii::$app->request->post('login_type', 3);
    if (empty($login_type) ) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    $user = Yii::$app->user->identity;
    if ($login_type == 3) {
      $user->openid_qq = '';
    } else if ($login_type == 4) {
      $user->openid_wx = '';
    } else if ($login_type == 5) {
      $user->openid_wb = '';
    }
    $user->save();
    return Re::data();
  }

  //重置密码
  public function actionResetPassword(){
    $phone = Yii::$app->request->post('phone', '');
    $code = Yii::$app->request->post('code', '');
    $password = Yii::$app->request->post('password', '');
    if (empty($phone) || empty($code) || empty($password)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    if (!PhoneCode::check($phone, $code)) {
      return Re::data(null, '验证码错误', Re::ERROR);
    }
    $user = Identity::findOne(['phone' => $phone, 'status' => 1]);
    if (!$user) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
    $user->password = Yii::$app->security->generatePasswordHash($password);
    if (!$user->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    return Re::data();
  }

  //账户注销
  public function actionCancel(){
    $user = Yii::$app->user->identity;
    $user->status = -1;
    $user->save();
    return Re::data();
  }

  //普通用户认证企业
  public function actionBindCompany(){
    $phone = Yii::$app->request->post('phone', '');
    $name = Yii::$app->request->post('name', '');
    $company_name = Yii::$app->request->post('company_name', '');
    $company_address = Yii::$app->request->post('company_address', '');
    $company_code = Yii::$app->request->post('company_code', '');
    $company_code_img = Yii::$app->request->post('company_code_img', '');
    if (empty($phone) || empty($name) || empty($company_name) || empty($company_address) || empty($company_code) || empty($company_code_img)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    $user = Yii::$app->user->identity;
    $user_auth_record_old = UserAuthRecord::find()->where(['phone' => $phone])->andWhere("user_id <> '$user->id'")->one();
    if ($user_auth_record_old) {
      return Re::data(null, '该手机号已被其他人认证', Re::ERROR);
    }
    $user_auth_record = UserAuthRecord::find()->where(['user_id' => $user->id])->one();
    if ($user_auth_record) {
      if (!$user_auth_record->audit_status) {
        return Re::data(null, '您提交的认证信息正在审核中，无需重复提交', Re::ERROR);
      }
      if ($user_auth_record->audit_status == 1) {
        return Re::data(null, '您提交的认证信息已审核通过，无需重复提交', Re::ERROR);
      }
    }
    $company_info = CompanyInfo::findOne(['code' => $company_code]);
    if (!$company_info) {
      $company_info = new CompanyInfo();
      $company_info->name = $company_name;
      $company_info->address = $company_address;
      $company_info->code = $company_code;
      $company_info->code_img = $company_code_img;
      $company_info->status = 1;
      $company_info->created_at = time();
      if (!$company_info->save()) {
        return Re::data(null, '企业信息保存失败', Re::ERROR);
      }
    }
    $user_auth_record = new UserAuthRecord();
    $user_auth_record->user_id = $user->id;
    $user_auth_record->phone = $phone;
    $user_auth_record->name = $name;
    $user_auth_record->company_id = $company_info->id;
    $user_auth_record->status = 1;
    $user_auth_record->created_at = time();

    $setting = Setting::findOne(1);
    if (!$setting->user_auth_audit) {//认证无需审核
      $user_auth_record->audit_status = 1;
      $user_auth_record->save();
      $user->name = $name;
      $user->company_id = $company_info->id;
      if (!$user->save()) {
        return Re::data(null, '操作失败', Re::ERROR);
      }
      return Re::data(['company_id' => $user->company_id]);
    }
    $user_auth_record->audit_status = 0;
    $user_auth_record->save();
    return Re::data();
  }

  //发送验证码
  public function actionSendCode(){
    $phone = Yii::$app->request->post('phone', '');
    $type = Yii::$app->request->post('type', 1);
    if (empty($phone)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    return PhoneCode::send($phone, $type);
    //return Re::data();
  }

  //意见反馈
  public function actionAddFeedBack(){
    $address = Yii::$app->request->post('address', '');
    $content = Yii::$app->request->post('content', '');
    $imgs = Yii::$app->request->post('imgs', '');
    $feed_back = new FeedBack();
    $feed_back->user_id = Yii::$app->user->id;
    $feed_back->address = $address;
    $feed_back->content = $content;
    $feed_back->imgs = $imgs;
    $feed_back->status = 1;
    $feed_back->created_at = time();
    $feed_back->save();
    return Re::data();
  }

  //意见反馈历史
  public function actionFeedBackList(){
    $feed_back_list = FeedBack::find()->where(['user_id' => Yii::$app->user->id, 'status' => 1])->all();
    $feed_back_data = [];
    if ($feed_back_list) {
      foreach ($feed_back_list as $v) {
        $feed_back_data[] = [
          'id' => $v->id,
          'content' => $v->content,
          'imgs' => $v->imgs ? explode(',', $v->imgs) : '',
          'created_time' => date("Y-m-d H:i:s", $v->created_at),
        ];
      }
    }
    return Re::data(['data' => $feed_back_data]);
  }

  //用户信息
  public function actionUserInfo(){
    $user = User::find()->where(['id' => Yii::$app->user->id, 'status' => 1])->one();
    if (!$user) {
      return Re::data(null, '用户信息异常', Re::ERROR);
    }
    $user_data = [
      'user_id' => (int)$user->id,
      'user_name' => $user->name,
      'user_phone' => $user->phone,
      'user_header' => $user->header,
      'user_birth' => $user->birth_day,
      'user_birth_string' => $user->birth_day ? date("Y/m/d", $user->birth_day) : '',
      'user_sex' => $user->sex,
      'user_sex_string' => $user->sex ? '男' : '女',
      'electric_code' => $user->electric_code,
      'company_id' => empty($user->company_id) ? '' : $user->company_id,
      'company_name' => $user->company_id ? $user->companyInfo->name : '',
      'company_code' => $user->company_id ? $user->companyInfo->code : '',
      'company_code_img' => $user->company_id ? $user->companyInfo->code_img : '',
      'company_address' => $user->company_id ? $user->companyInfo->address : '',
      'repair_id' => $user->repair_id,
      'is_admin' => $user->is_admin,
      'openid_qq' => $user->openid_qq,
      'openid_wx' => $user->openid_wx,
      'openid_wb' => $user->openid_wb,
    ];
    return Re::data(['data' => $user_data]);
  }

  //设置用户信息
  public function actionSetUserInfo(){
    $header = Yii::$app->request->post('user_header', '');
    $name = Yii::$app->request->post('user_name', '');
    $phone = Yii::$app->request->post('user_phone', '');
    $sex = Yii::$app->request->post('user_sex', -1);
    $birth_day = Yii::$app->request->post('user_birth', '');
    $electric_code = Yii::$app->request->post('electric_code', '');
    $user = Yii::$app->user->identity;
    if (!empty($header)) {
      $user->header = $header;
    }
    if (!empty($name)) {
      $user->name = $name;
    }
    if ($sex > -1) {
      $user->sex = $sex;
    }
    if (!empty($birth_day)) {
      $user->birth_day = $birth_day;
    }
    if (!empty($electric_code)) {
      $user->electric_code = $electric_code;
    }
    $user->save();
    return Re::data();
  }

  //常见问题
  public function actionQuestionList(){
    $question_list = Question::find()->where(['status' => 1])->orderBy('sort desc, created_at desc')->all();
    $question_data = [];
    if ($question_list) {
      foreach ($question_list as $v) {
        $question_data[] = [
          'title' => $v->title,
          'content' => $v->content,
        ];
      }
    }
    return Re::data(['data' => $question_data]);
  }

  private function returnUserInfo($user, $login_type=1) {
    if ($user && $user->phone) {
      Yii::$app->user->login($user);
      $token = UserLogin::generateToken($login_type);
      $data = [
        'bind_phone' => 1,
        'Authorization' => 'Bearer '.$token,
        'user_id' => (int)$user->id,
        'user_name' => $user->name,
        'user_phone' => $user->phone,
        'user_header' => $user->header,
        'company_id' => $user->company_id ?$user->company_id : '',
        'repair_id' => $user->repair_id,
        'is_admin' => $user->is_admin,
      ];
    } else {
      $data = [
        'bind_phone' => 0,
        'Authorization' => '',
        'user_id' => 0,
        'user_name' => '',
        'user_phone' => '',
        'user_header' => '',
        'company_id' => 0,
        'repair_id' => 0,
        'is_admin' => 0,
      ];
    }
    return $data;
  }
}
